package cn.cool.springframework.beans.factory.support;

import cn.cool.springframework.beans.BeansException;
import cn.cool.springframework.beans.factory.BeanFactory;
import cn.cool.springframework.beans.factory.config.BeanDefinition;

/**
 * AbstractBeanFactory 继承了 DefaultSingletonBeanRegistry，也就具备了使用单例注册类方法
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements BeanFactory {

    @Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null);
    }

    @Override
    public Object getBean(String name, Object... args) throws BeansException {
        return doGetBean(name, args);
    }

    protected <T> T doGetBean(final String name, final Object[] args) {
        Object bean = getSingleton(name);
        if (bean != null) {
            return (T) bean;
        }
        // 获取 BeanDefinition
        BeanDefinition beanDefinition = getBeanDefinition(name);
        // 返回创建的对象
        return (T) createBean(name, beanDefinition, args);
    }

    /**
     * 获取 BeanDefinition 定义信息
     */
    protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;

    /**
     * 根据 BeanDefinition去创建对象
     */
    protected abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException;
}
